package com.example.user.service.user;

import com.example.framework.common.constant.BaseHeaders;
import com.example.framework.redis.core.util.RedisUtils;
import com.example.framework.security.core.util.JwtTokenUtils;
import com.example.framework.security.core.util.SecurityFrameworkUtils;
import com.example.framework.web.core.util.WebFrameworkUtils;
import com.example.user.controller.basic.vo.HeartbeatReqVO;
import com.example.user.dal.redis.RedisKeyConstants;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.Optional;

@Service
public class HeartbeatService {

    @Resource
    private JwtTokenUtils jwtTokenUtils;

    public void receiveHeartbeat(HeartbeatReqVO heartbeatReqVO) {
        HttpServletRequest request = WebFrameworkUtils.getRequest();
        if (Objects.nonNull(request)) {
            String deviceId = Optional.ofNullable(request.getHeader(BaseHeaders.X_DEVICE_ID)).orElse("unknown");
            RedisUtils.set(generateRedisKey(deviceId), System.currentTimeMillis());
        }
        jwtTokenUtils.renewAccessToken(SecurityFrameworkUtils.getLoginUserId());
    }

    public Long getClientStatus(String clientId) {
        return RedisUtils.get(generateRedisKey(clientId), Long.class);
    }

    private String generateRedisKey(String clientId) {
        String userId = SecurityFrameworkUtils.getLoginUserId();
        return String.format("%s%s:%s", RedisKeyConstants.HEART_BEAT_KEY_PREFIX, userId, clientId);
    }
}
